package org.alex.samples.service;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;

import org.alex.samples.dao.IExamScoreDAO;
import org.alex.samples.dao.IExamSubjectDAO;
import org.alex.samples.dao.IExamUserDAO;
import org.alex.samples.javabean.ExamScoreVO;
import org.alex.samples.model.ExamScore;
import org.alex.samples.model.ExamSubject;
import org.alex.samples.model.ExamUser;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class ExamScoreServiceImpl implements IExamScoreService {

	@Autowired
	private IExamScoreDAO iExamScoreDAO;

	@Autowired
	private IExamUserDAO iExamUserDAO;

	@Autowired
	private IExamSubjectDAO iExamSubjectDAO;

	@Override
	public List<ExamScoreVO> getAllStudentScore() {
		List<ExamScore> examScores = iExamScoreDAO.find("from ExamScore");
		List<ExamScoreVO> examScoreVOs = new ArrayList<ExamScoreVO>();
		ExamScoreVO examScoreVO = null;
		for (ExamScore examScore : examScores) {
			examScoreVO = new ExamScoreVO();
			examScoreVO.setUserName(iExamUserDAO.get(examScore.getUserId()).getName());
			examScoreVO.setSubjectName(iExamSubjectDAO.get(examScore.getSubId()).getName());
			BeanUtils.copyProperties(examScore, examScoreVO);
			examScoreVO.setExamTimeString(examScore.getExamTime().toString());
			examScoreVOs.add(examScoreVO);
		}
		return examScoreVOs;
	}

	@Override
	public void deleteStudentScore(Integer scoreId) {
		ExamScore examScore = iExamScoreDAO.get(scoreId);
		if (examScore != null) {
			iExamScoreDAO.delete(examScore);
		}
	}

	@Override
	public List<ExamScoreVO> queryStudentScore(ExamScoreVO examScoreVO) {
		List<ExamScoreVO> examScoreVOs = new ArrayList<ExamScoreVO>();
		List<ExamScore> examScores = iExamScoreDAO.loadAll();
		ExamUser examUser = iExamUserDAO.get(examScoreVO.getUserId());
		ExamSubject examSubject = iExamSubjectDAO.get(examScoreVO.getSubId());
		DateFormat format = new SimpleDateFormat("yyyy-MM-dd");
		String examTime = null;
		ExamScoreVO scoreVO = null;
		if (examUser != null && examSubject != null) {
			for (ExamScore examScore : examScores) {
				examTime = format.format(examScore.getExamTime());
				if (examTime.equals(examScoreVO.getExamTimeString()) && examScore.getUserId().equals(examUser.getId())
						&& examScore.getSubId().equals(examSubject.getId())) {
					scoreVO = new ExamScoreVO();
					BeanUtils.copyProperties(examScore, scoreVO);
					scoreVO.setUserName(examUser.getName());
					scoreVO.setSubjectName(examSubject.getName());
					scoreVO.setExamTimeString(examScore.getExamTime().toString());
					examScoreVOs.add(scoreVO);
				}
			}
		}
		return examScoreVOs;
	}

}
